home *** CD-ROM | disk | FTP | other *** search
/ MACD 5 / MACD 5.bin / workbench / libs / unixlib.lha / unix / test / exec_test1.c < prev    next >
C/C++ Source or Header  |  1995-09-05  |  2KB  |  90 lines

  1. /* test program for exec() in unix.lib
  2.  *
  3.  * Launches as a child a program specified on the command line, redirecting
  4.  * its standard output (by mean of dup2()) to the file "pippo". The standard
  5.  * input is left indisturbed, so the child reads from the console and
  6.  * writes to "pippo".
  7.  */
  8.  
  9. #include <stdio.h>
  10. #include <errno.h>
  11. #include <stdlib.h>
  12. #include <unistd.h>
  13. #include <sys/wait.h>
  14. #include <proto/dos.h>
  15. #include <proto/exec.h>
  16.  
  17. typedef unsigned char bool;
  18.  
  19. #define FALSE 0
  20. #define TRUE  1
  21.  
  22. char *program;
  23.  
  24. void
  25. LogFatal(char *x0, char *x1)
  26. {
  27.     extern char *sys_errlist[];
  28.     static bool entered = FALSE;
  29.  
  30.     if (entered)
  31.         return;
  32.     entered = TRUE;
  33.  
  34.     fprintf(stderr, "%s: ", program);
  35.     if (errno)
  36.         fprintf(stderr, "%s: ", sys_errlist[ errno ]);
  37.     fprintf(stderr, x0,x1);
  38.     fprintf(stderr, "  Stop.\n");
  39.     exit(20);
  40. }
  41.  
  42. void
  43. LogFatalI(char *s, int i)
  44. {
  45.     /*NOSTRICT*/
  46.     LogFatal(s, (char *)i);
  47. }
  48.  
  49. int
  50. main(int ac, char **av)
  51. {
  52.     int pid, status;
  53.     char *comm;
  54.     char *argv[2];
  55.     FILE *outfp = fopen("pippo", "w");
  56.  
  57.     if (ac != 2) {
  58.         fprintf(stderr, "Usage: %s test-program\n", av[0]);
  59.         exit(EXIT_FAILURE);
  60.     }
  61.  
  62.     program = av[0];
  63.     comm = av[1];
  64.     argv[0] = av[1];
  65.     argv[1] = NULL;
  66.  
  67.     /* The exec() function in unix.lib starts a child process. */
  68.     /* It is possible to give the child input, output, current */
  69.     /* dir and stack different from the parent. If the input   */
  70.     /* or the output of the child are changed, they are closed */
  71.     /* after the child exits. Exec() returns the child pid.    */
  72.  
  73.     dup2(fileno(outfp), 1);
  74.     pid = exec(comm, argv, -1, -1, NULL, 4096);
  75.     if (pid < 0)
  76.         LogFatal("Cannot exec %s.", comm);
  77.     /* Simply wait child completion */
  78.     if (wait(&status) > 0) {
  79.         if (WIFSIGNALED(status))
  80.             LogFatalI("Signal %d.", WTERMSIG(status));
  81.         if (WIFEXITED(status) && WEXITSTATUS(status))
  82.             LogFatalI("Exit code %d.", WEXITSTATUS(status));
  83.     }
  84.  
  85.     fclose(outfp);
  86.     fprintf(stderr, "Job done.\n");
  87.     printf("Above is the output of the child.\n");
  88.     return(WEXITSTATUS(status));
  89. }
  90.